<template>
<div>
  <b-overlay :show="showload" rounded="sm">
  <b-card-header class="custom-info text-white font-weight-bold" @click="load()">健康上报</b-card-header>
  <b-card-body class="h-100">
  </b-card-body>
  <b-alert
      variant="danger"
      dismissible
      fade
      :show="showDismissibleAlert"
      @dismissed="showDismissibleAlert=false"
    >
      Dismissible Alert!
  </b-alert>

  <LoadingIcon v-if="loading"></LoadingIcon>
  <div v-else>
  <van-form @submit="onSubmit"  v-if="show">

  <van-field
  readonly
  :value="user.name"
  name='name'
  placeholder="钉钉人员信息"
  @click="getPerson"
/>
  <van-field
  readonly
  clickable
  :value="value"
  name='person'
  placeholder="选择人员"
  @click="showPicker = true"
  v-if="false"
/>
<van-popup v-model="showPicker" round position="bottom">
  <van-picker
    show-toolbar
    :columns="columns"
    @cancel="showPicker = false"
    @confirm="onConfirm"
  />
</van-popup>

  <van-field
    v-model="temp"
    name="temp"
    placeholder="今日体温℃"
    :rules="[{ required: true, message: '请填写今日体温℃' }]"
  />
  <van-field
    v-model="other"
    name="other"
    placeholder="备注"
  />
  <div style="margin: 16px;">
  <div>
     <Uploader ref="upload" v-if="false"></Uploader>
     <van-uploader 
     v-model="fileList" 
     :after-read="afterRead" 
     />
  </div>
  <b-card-body class="h-100">
  </b-card-body>
    <van-button round block type="success" native-type="submit">
      提交
    </van-button>
  </div>
</van-form>
<div v-else>
<van-divider dashed>今天未提交人员</van-divider>
<van-tabs title-active-color="#ee0a24">
  <van-tab v-for="value in notUpload" :title="value._id" :key="value._id">
    <van-grid :column-num="5">
  <van-grid-item v-for="value in value.name" :key="value" :text="value" />
</van-grid>
  </van-tab>
</van-tabs>

</div>
</div>
</b-overlay>
</div>
</template>

<script>
//import axios from 'axios'
import Uploader from '../components/Uploader'
import LoadingIcon from '../components/LoadingIcon'

export default {
  name: 'Upload',
  components: {
    Uploader,
    LoadingIcon
  },
  data() {
    return {
      config:null,
      loading: true,
      show:true,
      showload:false,
      showDismissibleAlert: false,
      name:'',
      temp: '',
      other:'',
      fileList: [
      ],
      value: '',
      valueArr: [],
      showPicker: false,
      columns: [
        {
          text: '中软',
          children: [
            {
              text: '大将'
            },
            {
              text: '北野'
            },
          ],
        },
        {
          text: '钉钉部',
          children: [
            {
              text: '小野',
            },
            {
              text: '东东'
            },
          ],
        },
      ],
      //images: this.$refs.upload.attachments,
      person:[],
      notUpload:[],
      user:{},
      url:{biz:'',userid:''}
    };
  },
  beforeCreate:function(){

  },
  created:function(){
  var url = window.location.href
  //var url ='http://www.baidu.com/?biz=1600499837250&userid=4546585158731071';
  if(url.split('?')[1]==undefined){
    //直接进入
  }else{
    //待办事项进入
    this.url.biz = url.split('=')[1].split('&')[0];
    this.url.userid = url.split('=')[2];
    //console.log(this.url)
    //this.updateWork(this.url);
  }
  
  //alert(url.split('?')[1]);
    if(this.$cookies.get('user')){
      //alert(JSON.stringify(this.$cookies.get('user')))
      this.user  = this.$cookies.get('user');
    }else{
      this.getUserId();
    }
    this.config = this.$root.$data.config;
    this.getNoUpload();
    this.loading = false;
    //this.getToken();
    //this.getUserId();
    this.getWork();
    //this.getData();
    //this.getUsers();
    //this.getAccess();
    //this.getUserId();
    //this.getCloudUsers();
  },
  mounted: function() {
    //console.log(this.$cookies.get('form'))
    //跨域问题
    //this.getToken()
    /*
    if(!this.$cookies.get('form')){
      alert('您的账号已过期，请重新输入')
      this.$cookies.set('login','false','1min')
      this.$router.push({ name: 'login'})
    }
    */
  },
  methods: {
  load(){
    //this.getNoUpload();
    this.show = !this.show;
  },
  async getNoUpload(){
    await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
    const cloud = this.$cloud
    this.$root.$data.cloud  = this.$cloud
    await cloud.callFunction({
      name: "getNoUpload"
    }).then(res=>{
      this.notUpload = res.result.list;
      //console.log(res)
    })
  },
  async getUsers(){
    await this.$tcb.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
      this.$root.$data.db = this.$tcb.database()
      const db = this.$tcb.database()
      //const _ = db.command

      const $ = db.command.aggregate
      db.collection('users').aggregate()
        .group({
          _id: '$dept',
          text:$.first('$dept'),
          children: $.addToSet({"text":'$name',"userid":'$userid'})
        })
        .end()
        .then(res=>{
        //console.log(res);
        this.columns = res.data;
        this.loading = false;
        //this.person = res.data
        }).catch(console.error)
  },
  async getData(){
    await this.$tcb.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
      this.$root.$data.db = this.$tcb.database()
      const db = this.$tcb.database()
      const _ = db.command

      const $ = db.command.aggregate
      db.collection('users').aggregate()
        .group({
          _id: '$dept',
          name: $.addToSet('$name') 
        })
        .end()
        .then(res=>{
        //console.log(res);
        this.person = res.data}).catch(console.error)
        const timeZero = new Date(new Date().toLocaleDateString()).getTime();
      db.collection('health').aggregate()
        .match({timestemp: _.gt(timeZero)})
        .group({
          _id: '$department',
          name: $.addToSet('$name') 
        })
        .end()
        .then(res=>{
          let aa = this.person;
          let bb = res.data;
          aa.map(x=>{bb.map(y=>{
            if(x._id===y._id){
              let xname = new Set(x.name);
              let yname = new Set(y.name);
              let array = Array.from(new Set([...xname].filter(x => !yname.has(x))));
              x.name =array
            }
          })})
        //console.log(aa)
        this.notUpload = aa
        this.loading = false;
        }).catch(console.error)
      
      //const db = this.$root.$data.db
      /*await db.collection("health").where({
        timestemp:_.gt(1600057824075)
      }).get()
      .then(res=>{console.log(res);})
      */
  },
  compare(id){
    return function(a,b){
        var value1 = a[id];
        var value2 = b[id];
        return value1 - value2;
    }
},
  onConfirm(value) {
      this.value = value.toString();
      this.valueArr = value;
      this.showPicker = false;
    },
    getUserId(){
      const dd = this.$root.$data.dd
      dd.ready(()=>{
          dd.runtime.permission.requestAuthCode({
              corpId: this.config.corpId, // 企业id
              onSuccess: info => {
                //调用云函数
                this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
                const cloud = this.$cloud
                cloud.callFunction({
                  name: "getUserId",
                  data:{code:info.code}
                }).then(res=>{
                  this.user = res.result;
                  this.$cookies.set('user',res.result,'2y')
                });
          }});
      });
    },
    getPerson(){
      this.show=true
      //获取人员信息
      const dd = this.$root.$data.dd
      const corpId = this.config.corpId;
      const that  = this;
      dd.ready(function(){
      dd.biz.contact.complexPicker({
            title:"人员选择",            //标题
            corpId:corpId,              //企业的corpId
            multiple:false,            //是否多选
            limitTips:"超出了",          //超过限定人数返回提示
            maxUsers:1000,            //最大可选人数
            pickedUsers:[],            //已选用户
            pickedDepartments:[],          //已选部门
            disabledUsers:[],            //不可选用户
            disabledDepartments:[],        //不可选部门
            requiredUsers:[],            //必选用户（不可取消选中状态）
            requiredDepartments:[],        //必选部门（不可取消选中状态）
            appId:158,              //微应用Id，企业内部应用查看AgentId
            permissionType:'GLOBAL',          //可添加权限校验，选人权限，目前只有GLOBAL这个参数
            responseUserOnly:true,        //返回人，或者返回人和部门
            startWithDepartmentId:-1 ,   //仅支持0和-1
            onSuccess: function(result) {
                console.log(result)
                that.name = result.users[0].name
                /**
                {
                    selectedCount:1,                              //选择人数
                    users:[{"name":"","avatar":"","userid":""}]，//返回选人的列表，列表中的对象包含name（用户名），avatar（用户头像），emplId（用户工号）三个字段
                    departments:[{"id":,"name":"","number":}]//返回已选部门列表，列表中每个对象包含id（部门id）、name（部门名称）、number（部门人数）
                }
                */
               this.show=true
            },
           onFail : function(err) {
            console.log(err)
            this.show=true
           }
        });
      })
        

    },
    async getCloudUsers(){
      await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
        const cloud = this.$cloud
        this.$root.$data.cloud  = this.$cloud
        await cloud.callFunction({
          name: "getUsers"
        }).then(res=>{console.log(res)})
    },
    async updateWork(url){
      await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
        const cloud = this.$cloud
        this.$root.$data.cloud  = this.$cloud
        await cloud.callFunction({
          name: "updateWorkRecord",
          data:{biz:url.biz,userid:url.userid}
        }).then(res=>{console.log(res)})
    },

    async getWork(){
      await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
        const cloud = this.$cloud
        this.$root.$data.cloud  = this.$cloud
        await cloud.callFunction({
          name: "sendWorkRecord"
        }).then(res=>{console.log(res)})
    },
    async getToken(){
      await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
      const cloud = this.$cloud
      this.$root.$data.cloud  = this.$cloud
      await cloud.callFunction({
        name: "getAuth",
        data: { url: this.config.url }
      }).then(res=>{console.log(res);this.getAccess();})
    },
    async getAccess(){
      const dd = this.$root.$data.dd
      await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
      const cloud = this.$cloud
      this.$root.$data.cloud  = this.$cloud
      await cloud.callFunction({
        name: "getAccess",
        data: { url: this.config.url }
      }).then(res=>{
        const param = res.result;
        dd.config({
              agentId: param.agentId, // 必填，微应用ID
              corpId: param.corpId,//必填，企业ID
              timeStamp: param.timeStamp, // 必填，生成签名的时间戳
              nonceStr: param.nonceStr, // 必填，生成签名的随机串
              signature: param.signature, // 必填，签名
              type:0,   //选填。0表示微应用的jsapi,1表示服务窗的jsapi；不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
              jsApiList : [
                  'runtime.info',
                  'biz.contact.choose',
                  'device.notification.confirm',
                  'device.notification.alert',
                  'device.notification.prompt',
                  'biz.ding.post',
                  'biz.util.openLink',
                  'biz.contact.complexPicker'
              ] // 必填，需要使用的jsapi列表，注意：不要带dd。
          });
      })
      
      /*
      axios.get(url)
        .then(resp => resp.data)
        .then(resp => {
          console.log(resp)
        })
      */
    },


    afterRead(file) {
      //console.log(file.content)
      file.status = 'uploading';
      file.message = '上传中...';
      setTimeout(() => {
        file.status = 'success';
        file.message = '上传成功';
      }, 1000);
      console.log(this.$tcb.uploadFile({
        cloudPath: '11.jpeg',
        fileContent: new Buffer(file.content, 'base64')
      }))
    },
    /** Triggered by custom 'form-submitted' event from GameForm child component. 
     * Parses formData, and route pushes to 'quiz' with formData as query
     * @public
     */
    handleFormSubmitted(formData) {
      const query = formData
      query.difficulty = query.difficulty.toLowerCase()
      this.$router.push({ name: 'quiz', query: query })
    },
    onSubmit(values) {
      //this.showDismissibleAlert = true;
      //this.loading = true;
      this.showload = true;
      values.department = this.user.dept;
      values.name = this.user.name;
      values.userid = this.user.userid;
      console.log('submit', values);
      //this.uploadHealth(values);
      this.updateUserlist(this.user.userid);
    },
    async updateUserlist(userid){
      await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
      const cloud = this.$cloud
      this.$root.$data.cloud  = this.$cloud
      await cloud.callFunction({
        name: "updateUserlist",
        data: { userid: userid }
      }).then(()=>{
        if(this.url.biz){this.updateWork(this.url);}
        this.showload = false;
        this.$bvToast.toast(`上传成功`, {
          title:'Health',
          autoHideDelay: 2000,
          //toaster: 'b-toaster-bottom-center',
          variant:'primary',
          solid: true,
        })
        this.name = '';
        this.value = '';
        this.fileList = [];
        this.temp = '';
        this.other = '';
      })
    },
    async uploadHealth(value){
      let time = new Date();
      value.timestemp = time.getTime();
      value.creatTime = time.toLocaleString();
      //const db = this.$root.$data.db
      await this.$tcb.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
      this.$root.$data.db = this.$tcb.database()
      const db = this.$tcb.database()

      await db.collection('health').add(value)
      .then(()=>{
        if(this.url.biz){this.updateWork(this.url);}
      this.showload = false;
      this.$bvToast.toast(`上传成功`, {
          title:'Health',
          autoHideDelay: 2000,
          //toaster: 'b-toaster-bottom-center',
          variant:'primary',
          solid: true,
        })
        this.name = '';
        this.value = '';
        this.fileList = [];
        this.temp = '';
        this.other = '';
      })
      this.getNoUpload();
    },
  }
}
</script>

